package handle

import (
	"encoding/json"
	"log"
	"net"
	"os"
	"path/filepath"

	obj "ifile/object"
)

// Handler 文件流接收处理
type Handler struct {
	RootPath string
}

// MakeFileHandler 创建处理器
func MakeFileHandler(rootPath string) *Handler {
	return &Handler{
		RootPath: rootPath,
	}
}

// WriteFile tcp接收处理
func (h *Handler) Handle(conn net.Conn, head []byte) error {
	meta := obj.Meta{}
	err := json.Unmarshal(head, &meta)
	if err != nil {
		log.Println("解析消息错误！err: ", err)
		return err
	}

	filePath := filepath.Join(h.RootPath, meta.Sha1)

	fp, err := os.OpenFile(filePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
	if err != nil {
		log.Println(err)
		return err
	}
	defer fp.Close()

	var readSize int64 = 0

	for readSize < meta.Size {
		buf := make([]byte, 2048)
		n, err := conn.Read(buf)
		if err != nil {
			break
		}
		readSize += int64(n)

		_, err = fp.Write(buf)
		if err != nil {
			log.Printf("写文件错误，err: %v", err)
			break
		}

		// TODO 文件检验
	}
	log.Println("文件读取完成，文件路径: ", meta.Path)
	return nil
}
